package com.atguigu.bookcity.service.impl;

import com.atguigu.bookcity.entity.Inventory;
import com.atguigu.bookcity.entity.vo.InventoryVo;
import com.atguigu.bookcity.mapper.InventoryMapper;
import com.atguigu.bookcity.service.InventoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zsc
 * @since 2021-06-05
 */
@Service
@Transactional
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {

    @Resource
    private InventoryMapper inventoryMapper;

    @Override
    public List<InventoryVo> listByBookIds(List<String> ids) {
        return inventoryMapper.listByBookIds(ids);
    }

    @Override
    public List<InventoryVo> selectInventories() {
        return inventoryMapper.selectInventories();
    }

    @Override
    public List<InventoryVo> listByBookNames(List<String> names) {
        return inventoryMapper.listByBookNames(names);
    }

    @Override
    public List<InventoryVo> getInventoriesLikeName(String name) {
        return inventoryMapper.getInventoriesLikeName(name);
    }

    @Override
    public List<InventoryVo> getNotEnoughInventories(Integer from, Integer to) {
        if (from == null)
            from = 0;
        return inventoryMapper.getNotEnoughInventories(from, to);
    }

    @Override
    public void addInventories(List<Inventory> inventories) {
        List<String> inventoriesIds = inventories
                .stream()
                .map(Inventory::getBookId)
                .collect(Collectors.toList());
        List<Inventory> dbInventories = listByIds(inventoriesIds);
        dbInventories.forEach(dbInventory -> {
            for (Inventory inventory : inventories) {
                if (inventory.getBookId().equals(dbInventory.getBookId())) {
                    dbInventory.setNumber(dbInventory.getNumber() + inventory.getNumber());
                    break;
                }
            }
        });
        updateBatchById(dbInventories);
    }

    @Override
    public void removeInventoriesNotInBooks() {
        inventoryMapper.removeInventoriesNotInBooks();
    }
}
